<template>
<div>
  <!--面包屑导航-->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>参数管理</el-breadcrumb-item>
    <el-breadcrumb-item>参数列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!--卡片-->
  <el-card>
    <el-alert type="warning" title="请注意：只可以为三级分类添加参数！" :close="false" show-icon ></el-alert>
    <el-row>
      <el-col>
        <span>请选择商品分类：</span>
        <!--级联选择框-->
        <el-cascader
        v-model="selectedKeys"
        :options="cateList"
        :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children' }"
        @change="handleChange"></el-cascader>
       </el-col>
    </el-row>
    <!--tabs页签-->
    <el-tabs v-model="activeName" @tab-click="handleTabsClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="setAttrDialogVisible = true">添加参数</el-button>
        <el-table :data="manyTableData" border stripe>
          <el-table-column type="expand">
            <template v-slot="scope">
              <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="deleteAttr(index,scope.row)">{{item}}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="ID"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="setAttrDialogVisible = true">添加属性</el-button>
        <el-table :data="onlyTableData" border stripe>
          <el-table-column type="expand">
            <template v-slot="scope">
              <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="deleteAttr(index,scope.row)">{{item}}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="ID"></el-table-column>
          <el-table-column label="属性名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>
  <!--添加动态参数/静态属性对话框-->
  <el-dialog
  :title="'添加' + title"
  :visible.sync="setAttrDialogVisible"
  width="30%"
  @close="setAttrDialogClosed">
  <el-form :model="attrForm" :rules="attrFormRules" ref="attrFormRef" label-width="100px">
  <el-form-item :label="title" prop="attr_name">
    <el-input v-model="attrForm.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setAttrDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setAttrParams">确 定</el-button>
  </span>
</el-dialog>
<!--修改动态参数/静态属性对话框-->
  <el-dialog
  :title="'修改' + title"
  :visible.sync="editAttrDialogVisible"
  width="30%"
  @close="editAttrDialogClosed">
  <el-form :model="editAttrForm" :rules="editAttrFormRules" ref="editAttrFormRef" label-width="100px">
  <el-form-item :label="title" prop="attr_name">
    <el-input v-model="editAttrForm.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editAttrDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editAttrParams">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      selectedKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      setAttrDialogVisible: false,
      attrForm: { attr_name: '' },
      attrFormRules: {
        attr_name: [
          { required: true, message: '名称必须填写', trigger: 'blur' }
        ]
      },
      editAttrDialogVisible: false,
      editAttrForm: { attr_name: '' },
      editAttrFormRules: {
        attr_name: [
          { required: true, message: '名称必须填写', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: result } = await this.$http.get('categories')
      if (result.meta.status !== 200) {
        return this.$message.error('获取分类信息失败！')
      }
      this.cateList = result.data
    },
    handleChange () {
      this.getParamsData()
    },
    handleTabsClick () {
      this.getParamsData()
    },
    async getParamsData () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      const { data: result } = await this.$http.get(`categories/${this.catId}/attributes`, { params: { sel: this.activeName } })
      if (result.meta.status !== 200) {
        return this.$message.error('获取参数信息失败！')
      }
      result.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = result.data
      } else {
        this.onlyTableData = result.data
      }
    },
    setAttrDialogClosed () {
      this.$refs.attrFormRef.resetFields()
    },
    setAttrParams () {
      this.$refs.attrFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const { data: result } = await this.$http.post(`categories/${this.catId}/attributes`, { attr_name: this.attrForm.attr_name, attr_sel: this.activeName })
        if (result.meta.status !== 201) {
          return this.$message.error('添加失败！')
        }
        this.$message.success('添加成功！')
        this.getParamsData()
        this.editAttrDialogVisible = false
      })
    },
    editAttrParams () {
      this.$refs.editAttrFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const { data: result } = await this.$http.put(`categories/${this.catId}/attributes/${this.editAttrForm.attr_id}`, { attr_name: this.editAttrForm.attr_name, attr_sel: this.activeName })
        if (result.meta.status !== 200) {
          return this.$message.error('修改失败！')
        }
        this.$message.success('修改成功！')
        this.getParamsData()
        this.editAttrDialogVisible = false
      })
    },
    editAttrDialogClosed () {
      this.$refs.editAttrFormRef.resetFields()
    },
    async showEditDialog (attrId) {
      const { data: result } = await this.$http.get(`categories/${this.catId}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
      if (result.meta.status !== 200) {
        return this.$message.error('获取信息失败！')
      }
      this.editAttrForm = result.data
      this.editAttrDialogVisible = true
    },
    async removeParams (attrId) {
      const res = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res !== 'confirm') {
        return this.$message.info('取消删除！')
      }
      const { data: result } = await this.$http.delete(`categories/${this.catId}/attributes/${attrId}`)
      if (result.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getParamsData()
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      row.attr_vals.push(' ', row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttr(row)
    },
    showInput (scope) {
      scope.inputVisible = true
      // 自动获取焦点，$nextTick：当页面渲染完毕以后才会调用回调函数获取页面焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveAttr (row) {
      const { data: result } = await this.$http.put(`categories/${this.catId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join('') })
      if (result.meta.status !== 200) {
        return this.$message.error('修改失败！')
      }
      this.$message.success('修改成功！')
    },
    deleteAttr (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttr(row)
    }
  },
  computed: {
    isBtnDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    catId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    title () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin: 15px 0;
}
.input-new-tag {
  width: 120px;
}
.el-tag {
  margin: 0 10px;
}
</style>
